<?php

class AgentRechargeController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout='//layouts/main';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('index', 'view'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('create'),
                'users' => array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('admin'),
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new AgentRecharge;
        $modelB = new CardInfo;
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        if (isset($_POST['AgentRecharge']) || isset($_POST['CardInfo'])) {
        	 $model->attributes = $_POST['AgentRecharge'];
        	 $modelB->attributes = $_POST['CardInfo'];
        	 //这是admin用户代充代码 flag 和 tag 均是url传递参数，起到控制多用
            if(!isset($_GET['flag']) || $_GET['tag'] == '1'){ 
                //充值成功后给用户添加金额
                //AgentRecharge::model()->beforeSave();
                if ($_GET['flag'] == 1) {
                    $model->recharge_time = date('Y-m-d H:i:s');
                }
                if(isset($_GET['custom_id'])){
                    $model->agent_id = $_GET['custom_id'];
                    $model->user_id=$_GET['user_id'];
                }
                $model->txnid=date(Ymdhis);
                $model->crate_time = date('Y-m-d H:i:s');
                $model->is_delete = 0;
                $model->crate_user = User::model()->getUserName(yii::app()->user->id);
                AgentRecharge::model()->rechangeSuccess();  //充值成功后，修改内容
                if ($model->save()){
                    if($_GET['tag'] == '1'){
                         $this->redirect(array('custom/admin','isreback'=>0));
                    }else{
                         $this->redirect(array('User/admin','level'=>$_GET['level']));
                    }
                }
            }else{
            $sql = "select * from zy_card_info where user_id=" . yii::app()->request->getParam("user_id");
            $results = Yii::app()->db->createCommand($sql)->queryAll();
            //绑定信用卡信息代码块
            if(!empty($_POST['CardInfo']['card_number'])){
            	$user_id = yii::app()->request->getParam("user_id");
            	if(!empty($results)){
            	if($results[0]['user_id'] == $user_id){
            		//删除
            		CardInfo::model()->findByPk($results[0]['card_info_id'])->delete();
            	}
              }
              	//插入
            	$modelB->user_id = yii::app()->request->getParam("user_id");
			    $modelB->create_time = date('Y-m-d H:i:s');
			    $modelB->card_type= $model->recharge_type;
		        $modelB->save();
            }
            // 比对是否是用过押金付款方式，如果使用过，返回提示，无法使用押金付款充值
            $recharge=  AgentRecharge::model()->find('user_id='.yii::app()->user->id .' and recharge_type = 3');
            if($_POST['AgentRecharge']['recharge_type'] == $recharge['recharge_type']){
                 $this->redirect(array('create','message'=>3,'user_id'=>yii::app()->user->id,'flag'=>'3G'));
            }
            $sql = "select * from zy_card_info where user_id=" . yii::app()->request->getParam("user_id");
            $result = Yii::app()->db->createCommand($sql)->queryAll();
             $params = array(   //设置充值参数
                //金额 发票id  流水号
                "amount" => $model->recharge_number,
                "invoiceid" =>date('YmdHis'),
                "invoiceref" =>  date('YmdHis'),
                //信用卡
                "cardnum" => $result[0]['card_number'],
                "cardexp" => $result[0]['expirydate'],
                //转账参数
                "cc_bsbnumber" => $result[0]["card_bsbnumber"],
                "cc_accountnumber" => $result[0]["card_accountnumber"],
                "cc_accountname" => $result[0]["card_accountname"],
            );
            //充值参数 如果未绑定信用卡或银行卡，返回错误提示
            //recharge_type == 1.信用卡 2.银行卡 3.押金付款
            if($_POST['AgentRecharge']['recharge_type'] !=3){
            if($_POST['AgentRecharge']['recharge_type'] == 2 && empty($result[0]["card_bsbnumber"])){ //银行卡
                if($_GET['flag'] == '3G'){
                    $this->redirect(array('create', 'fail_message'=>1,'message'=>1,'user_id'=>yii::app()->user->id,'flag'=>'3G'));
                }else{
                    $this->redirect(array('create', 'fail_message'=>1,'message'=>1,'user_id'=>yii::app()->user->id,'flag'=>1));
                }
            }
            if($_POST['AgentRecharge']['recharge_type'] == 1 && empty($result[0]['card_number'])){  //信用卡
                 if($_GET['flag'] == '3G'){
                     $this->redirect(array('create', 'fail_message'=>1,'message'=>2,'user_id'=>yii::app()->user->id,'flag'=>'3G'));
                }else{
                     $this->redirect(array('create', 'fail_message'=>1,'message'=>2,'user_id'=>yii::app()->user->id,'flag'=>1));
                }
            }
           }
           
            if($_POST['AgentRecharge']['recharge_type']==1  && $result[0]['card_number'] != ""){
                $payment_result = AgentRecharge::model()->cc_capture($params); //执行信用卡充值
            }else if($_POST['AgentRecharge']['recharge_type']==2  && $result[0]["card_bsbnumber"] != ""){
           	$payment_result = AgentRecharge::model()->cc_bankpay($params); //执行银行卡充值
            }
            
           // check payment result
            if ($payment_result['status'] == "success" || $_POST['AgentRecharge']['recharge_type']==3)
            {
                //充值成功后给用户添加金额
                //AgentRecharge::model()->beforeSave();
                if ($_GET['flag'] == 1) {
                    $model->recharge_time = date('Y-m-d H:i:s');
                    $model->txnid=date(Ymdhis);
                }else if($_GET['flag'] == '3G'){
                	  $model->recharge_time = date('Y-m-d H:i:s');
                      $model->txnid=$payment_result['txnid'];
                }else{
                	 $model->txnid=$payment_result['txnid'];
                }
                $model->crate_time = date('Y-m-d H:i:s');
                $model->is_delete = 0;
                $model->crate_user = User::model()->getUserName(yii::app()->request->getParam("user_id"));
                AgentRecharge::model()->rechangeSuccess();  //充值成功后，修改内容
                if ($model->save())
                    if(yii::app()->user->level3() == 8){
                         $this->redirect(array('admin','flag'=>'3G'));
                    }else{
                         $this->redirect(array('admin'));
                    }
                }else if ($payment_result['status'] == "fail"){
                    if(yii::app()->user->level3() == 8){
                         $this->redirect(array('create', 'fail_message'=>1,'user_id'=>yii::app()->user->id,'flag'=>'3G'));
                    }else{
                         $this->redirect(array('create', 'fail_message'=>1,'user_id'=>yii::app()->user->id,'flag'=>1));
                    }
                }else{
                      if(yii::app()->user->level3() == 8){
                          $this->redirect(array('create', 'fail_message'=>2,'user_id'=>yii::app()->user->id,'flag'=>'3G'));
                    }else{
                          $this->redirect(array('create', 'fail_message'=>2,'user_id'=>yii::app()->user->id,'flag'=>1));
                    }
                }
           }
        }

        $this->render('create', array(
            'model' => $model,
            'modelB'=>$modelB,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['AgentRecharge'])) {
            $model->attributes = $_POST['AgentRecharge'];
            if ($model->save())
                $this->redirect(array('view', 'id' => $model->agent_recharge_id));
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        $this->loadModel($id)->delete();

        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if (!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('AgentRecharge');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new AgentRecharge('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['AgentRecharge']))
            $model->attributes = $_GET['AgentRecharge'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer $id the ID of the model to be loaded
     * @return AgentRecharge the loaded model
     * @throws CHttpException
     */
    public function loadModel($id) {
        $model = AgentRecharge::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param AgentRecharge $model the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'agent-recharge-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}
